package com.yxsd.service.impl;

import com.pandawork.core.exception.SSException;
import com.pandawork.core.log.LogClerk;
import com.pandawork.core.util.CommonUtil;
import com.yxsd.common.entity.Admin;
import com.yxsd.common.exception.YxsdException;
import com.yxsd.common.service.impl.BaseServiceImpl;
import com.yxsd.mapper.AdminMapper;
import com.yxsd.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * AdminServiceImpl
 *
 * @author: zhangteng
 * @time: 2015/1/4 18:08
 */
@Service("adminService")
public class AdminServiceImpl extends BaseServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public void add(Admin admin) throws SSException {
        try {
            String pwd = admin.getPwd();
            pwd = CommonUtil.md5(pwd);
            admin.setPwd(pwd);
            this.insert(admin);
        } catch (Exception e) {
            LogClerk.errLog.error(e);
            throw SSException.get(YxsdException.SystemException, e);
        }
    }

    @Override
    public Admin login(Admin admin) throws SSException {
        try {
            admin.setPwd(CommonUtil.md5(admin.getPwd()));
            Integer id = adminMapper.chekcLogin(admin);
            if (id != null) {
                admin.setId(id);
                return admin;
            } else {
                return null;
            }
        } catch (Exception e) {
            LogClerk.errLog.error(e);
            throw SSException.get(YxsdException.SystemException, e);
        }
    }

    @Override
    public boolean modifyPwd(Integer adminId, String newPwd, String oldPwd) throws SSException {
        try {
            Admin admin = this.queryById(Admin.class, adminId);
            newPwd = CommonUtil.md5(newPwd);
            oldPwd = CommonUtil.md5(oldPwd);
            if (!admin.getPwd().equals(oldPwd)) {
                return false;
            }
            admin.setPwd(newPwd);
            this.update(admin);
            return true;
        } catch (Exception e) {
            LogClerk.errLog.error(e);
            throw SSException.get(YxsdException.SystemException, e);
        }
    }
}
